package com.xianxing.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * date 2020/3/7
 * auth 李金全
 * 日期工具类
 */
public class DateUtil {

    /**
     * yyyy-MM-dd:HH:mm字符串转yyyyMMddHH
     * @param date
     * @return
     */
    public static String formatStr(String date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm");
        try {
            Date format = simpleDateFormat.parse(date);
            SimpleDateFormat yyyyMMddHH = new SimpleDateFormat("yyyyMMddHH");
            return yyyyMMddHH.format(format);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取指定日期的凌晨
     * @param date
     * @return
     */
    public static Date toDateStartHour(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        return calendar.getTime();
    }

    /**
     * 增加当前时间的分钟
     * @param date
     * @param minutes
     * @return
     */
    public static Date addDateMinutes(Date date,int minutes){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE,minutes);
        return calendar.getTime();
    }

    /**
     * 时间递增N小时
     * @param date
     * @param hours
     * @return
     */
    public static Date addDateHours(Date date,int hours){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR,hours);
        return calendar.getTime();
    }

    /**
     * 获取时间菜单 开始时间<=当前时间<开始时间+2
     * @return
     */
    public static List<Date> getDateMenus(){
        List<Date> dates = new ArrayList<Date>();

        Date date = toDateStartHour(new Date());
        for (int i = 0; i < 12; i++) {
            dates.add(addDateHours(date,i*2));
        }
        //判断当前时间属于哪个时间点的范围
        Date now = new Date();
        for (Date date1 : dates) {
            //开始时间<=当前时间<开始时间+2小时
            if(date1.getTime()<=now.getTime()&&now.getTime()<addDateHours(date1,2).getTime()){
                now =date1;
                break;
            }
        }
        //将开始时间之后的五个时间点存入集合
        ArrayList<Date> menus = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            menus.add(addDateHours(now,i*2));
        }
        //返回菜单
        return menus;
    }

    /**
     * 时间转换为字符串 yyyyMMddHH
     * @param date
     * @return
     */
    public static String date2Str(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHH");
        return format.format(date);
    }
}
